package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.config.WxOpenConfig;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.mapper.SysteminfoMapper;
import com.yupi.springbootinit.mapper.VipuserlistMapper;
import com.yupi.springbootinit.model.dto.user.*;
import com.yupi.springbootinit.model.entity.Systeminfo;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.entity.Vipuserlist;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.AnonnameService;
import com.yupi.springbootinit.service.UserService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yupi.springbootinit.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import static com.yupi.springbootinit.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private WxOpenConfig wxOpenConfig;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        String phoneNumber = userRegisterRequest.getPhoneNumber();
        String checkCode = userRegisterRequest.getCheckCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, phoneNumber, checkCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, phoneNumber, checkCode);
        return ResultUtils.success(result);
    }

    @Resource
    private AnonnameService anonnameService;

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);

        return ResultUtils.success(loginUserVO);
    }

//    /**
//     * 用户登录（微信开放平台）
//     */
//    @GetMapping("/login/wx_open")
//    public BaseResponse<LoginUserVO> userLoginByWxOpen(HttpServletRequest request, HttpServletResponse response,
//            @RequestParam("code") String code) {
//        WxOAuth2AccessToken accessToken;
//        try {
//            WxMpService wxService = wxOpenConfig.getWxMpService();
//            accessToken = wxService.getOAuth2Service().getAccessToken(code);
//            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
//            String unionId = userInfo.getUnionId();
//            String mpOpenId = userInfo.getOpenid();
//            System.out.println("unionId: " + unionId);
//            System.out.println("mpOpenId: " + mpOpenId);
//            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
//                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
//            }
//            return ResultUtils.success(userService.userLoginByMpOpen(userInfo, request));
//        } catch (Exception e) {
//            log.error("userLoginByWxOpen error", e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
//        }
//    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }


    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }


    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }


    /**
     * 更新个人信息
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestParam(required = false) String userName, @RequestParam(required = false) MultipartFile userAvatar,
                                              HttpServletRequest request) {
        if (userName == null && userAvatar == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        if (user.getUserPoints() < 10) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "积分不足");
        }
        if (userName != null) {
            List<String> sensitiveWords = Arrays.asList(// 违反法律法规类
                    "法轮功", "全能神", "华藏宗门", "冰毒", "海洛因", "大麻", "制毒", "贩毒", "P2P暴雷", "虚拟货币挖矿", "民间标会倒会", "套路贷",
                    // 危害国家安全与社会稳定类
                    "港独", "台独", "蒙独", "疆独", "反动会道门", "恶意诋毁国家政策", "抹黑医保改革", "唱衰国企",
                    // 低俗色情类
                    "阴茎", "睾丸", "阴道", "阴蒂", "做爱", "性交", "口交", "肛交", "自慰", "一夜情", "嫖娼", "约炮", "乳沟", "翘臀", "丝袜诱惑",
                    "苍井空", "波多野结衣", "小泽玛利亚", "武藤兰", "AV女优", "成人影片", "三级片", "黄片", "色情直播", "裸聊", "露点", "性感内衣秀",
                    "性癖好", "性虐待", "SM", "淫荡", "风骚", "狐狸精", "荡妇", "牛郎", "鸭店", "色情按摩", "情趣用品",
                    "AV", "ML", "FJ", "KJ", "约P", "PC", "黄播", "色Q",
                    // 暴力恐怖类
                    "基地组织", "伊斯兰国", "博科圣地", "斩首", "肢解", "枪杀", "纵火", "爆炸", "绑架勒索", "持械抢劫",
                    // 网络诈骗类
                    "刷单返现骗局", "网络兼职诈骗", "冒充公检法诈骗", "交友杀猪盘", "荐股诈骗", "跑分", "赌博", "彩票",
                    // 知识产权侵权类
                    "山寨苹果手机", "假耐克运动鞋", "盗版微软系统", "未经授权翻拍某电影", "盗版某热门小说", "盗录某演唱会音频",
                    // 人身攻击与歧视类
                    "黑鬼", "白皮猪", "男尊女卑", "女权癌", "娘炮", "弱女子", "瘸子", "瞎子", "聋子", "弱智",
                    // 不实信息与谣言类
                    "某地发生9级地震", "某明星去世", "吃绿豆治百病", "喝醋软化血管", "永动机研发成功", "量子速读提升学习能力",
                    // 广告垃圾信息类
                    "特效抗癌药", "根治糖尿病神药", "一周瘦十斤减肥药", "三个月长高10厘米增高药", "加微信免费领礼品", "点击链接获取巨额奖金"); // 示例敏感词列表
            if (containsSensitiveWords(userName, sensitiveWords)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容包含敏感词");
            }

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userName);
            long count = userService.count(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
            }
            //这里在更改用户名时，用户名与账号是一直的
            user.setUserName(userName);
            user.setUserAccount(userName);
        }
        if (userAvatar != null) {
            if (user.getUserAvatar() != null) {
                userService.deleteUserImage(user.getUserAvatar());
            }
            user.setUserAvatar(userService.uploadUserImage(userAvatar));
        }
        user.setUserPoints(user.getUserPoints() - 10);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 判断文本是否包含敏感词
     *
     * @param text
     * @param sensitiveWords
     * @return
     */
    private boolean containsSensitiveWords(String text, List<String> sensitiveWords) {
        if (StringUtils.isBlank(text)) {
            return false;
        }
        for (String word : sensitiveWords) {
            if (text.contains(word)) {
                return true;
            }
        }
        return false;
    }


    @PostMapping("/beadmin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> beAdmin(@RequestParam(required = false) String userId,@RequestParam(required = false) String userName, @RequestParam(required = false) String phoneNum, HttpServletRequest request) {

        if (userName == null && phoneNum == null&& userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userName != null) {
            queryWrapper.eq("userName", userName);
        } else if (phoneNum != null) {
            queryWrapper.eq("phoneNum", phoneNum);
        }else if (userId != null){
            queryWrapper.eq("id", userId);
        }
        User user = userService.getOne(queryWrapper);
        user.setUserRole(UserConstant.ADMIN_ROLE);
        userService.updateById(user);

        QueryWrapper<Vipuserlist> vipquery = new QueryWrapper<>();
        vipquery.eq("userId", user.getId());
        Vipuserlist vipuser = vipuserlistMapper.selectOne(vipquery);
        if (vipuser != null){
            vipuserlistMapper.deleteById(vipuser.getId());
        }
        return ResultUtils.success("已升级为管理员用户-" + user.getId() + "-" + user.getUserName());
    }

    @Resource
    private VipuserlistMapper vipuserlistMapper;
    /**
     * 用户还原为user或解禁
     */
    @PostMapping("/reuser")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> reUser(@RequestParam(required = false) String userId,@RequestParam(required = false) String userName, @RequestParam(required = false) String phoneNum, HttpServletRequest request) {

        if (userName == null && phoneNum == null&& userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userName != null) {
            queryWrapper.eq("userName", userName);
        } else if (phoneNum != null) {
            queryWrapper.eq("phoneNum", phoneNum);
        }else if (userId != null){
            queryWrapper.eq("id", userId);
        }
        User user = userService.getOne(queryWrapper);
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        userService.updateById(user);

        QueryWrapper<Vipuserlist> vipquery = new QueryWrapper<>();
        vipquery.eq("userId", user.getId());
        Vipuserlist vipuser = vipuserlistMapper.selectOne(vipquery);
        if (vipuser != null){
            vipuserlistMapper.deleteById(vipuser.getId());
        }
        return ResultUtils.success("已还原为普通用户-" + user.getId() + "-" + user.getUserName());
    }

    /**
     * 用户升级为vip
     */
    @PostMapping("/vip")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> vip(@RequestParam(required = false) String userId,@RequestParam(required = false) String userName, @RequestParam(required = false) String phoneNum, HttpServletRequest request) {

        if (userName == null && phoneNum == null&& userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userName != null) {
            queryWrapper.eq("userName", userName);
        } else if (phoneNum != null) {
            queryWrapper.eq("phoneNum", phoneNum);
        }else if (userId != null){
            queryWrapper.eq("id", userId);
        }
        User user = userService.getOne(queryWrapper);
        user.setUserRole(UserConstant.VIP_ROLE);
        userService.updateById(user);
        Vipuserlist vipuserlist = new Vipuserlist();
        vipuserlist.setUserId(user.getId());
        vipuserlist.setUserName(user.getUserName());
        vipuserlist.setPhonenum(user.getPhoneNum());
        vipuserlistMapper.insert(vipuserlist);

        return ResultUtils.success("已升级为vip");
    }

    @PostMapping("/ban")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> ban(@RequestParam(required = false) String userId,@RequestParam(required = false) String userName, @RequestParam(required = false) String phoneNum, HttpServletRequest request) {

        if (userName == null && phoneNum == null&& userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userName != null) {
            queryWrapper.eq("userName", userName);
        } else if (phoneNum != null) {
            queryWrapper.eq("phoneNum", phoneNum);
        }else if (userId != null){
            queryWrapper.eq("id", userId);
        }
        User user = userService.getOne(queryWrapper);
        user.setUserRole(UserConstant.BAN_ROLE);
        userService.updateById(user);

        QueryWrapper<Vipuserlist> vipquery = new QueryWrapper<>();
        vipquery.eq("userId", user.getId());
        Vipuserlist vipuser = vipuserlistMapper.selectOne(vipquery);
        if (vipuser != null){
            vipuserlistMapper.deleteById(vipuser.getId());
        }
        return ResultUtils.success("已封禁用户-" + user.getId() + "-" + user.getUserName());
    }

    /**
     * 忘记密码,验证手机号和验证码，然后修改密码
     *
     * @param forgetPasswordRequest
     * @param request
     * @return
     */
    @PostMapping("/forgetPassword")
    public BaseResponse<String> forgetPassword(@RequestBody ForgetPasswordRequest forgetPasswordRequest, HttpServletRequest request) {
        String userPassword = forgetPasswordRequest.getUserPassword();
        String checkPassword = forgetPasswordRequest.getCheckPassword();
        String phoneNumber = forgetPasswordRequest.getPhoneNumber();
        String checkCode = forgetPasswordRequest.getCheckCode();
        if (StringUtils.isAnyBlank(phoneNumber,userPassword, checkPassword,  checkCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        boolean b = userService.forgetPassword(phoneNumber,userPassword, checkPassword,  checkCode);
        return ResultUtils.success("密码修改成功");

    }

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysteminfoMapper systeminfoMapper;

    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @GetMapping("/sendCode")
    public BaseResponse<String> sendMessage(@RequestParam(required = true) String phone) throws Exception {
        if (phone.length() < 10|| phone.length() > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }
        if (redisTemplate.hasKey("yzm" + phone)) {
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR, "验证码已发送，请勿重复请求");
        }

        String code = SMSUtils.sendSms(phone);
        //使用redis 存起来，过期时间300秒，用于登录时拿出来验证
        redisTemplate.opsForValue().set("yzm" + phone, code, 300, TimeUnit.SECONDS);

        QueryWrapper<Systeminfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("createTime"); // 根据创建时间降序排序
        queryWrapper.last("LIMIT 1"); // 限制结果数量为 1
        Systeminfo latestRecord = systeminfoMapper.selectOne(queryWrapper);
        if (latestRecord != null) {
            latestRecord.setSendSmsNum(latestRecord.getSendSmsNum() + 1);
            systeminfoMapper.updateById(latestRecord);
        }

        return ResultUtils.success("验证码发送成功");
    }

}
